﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Account : System.Web.UI.Page
{
    debioscoopEntities db;
    protected void Page_Init(object sender, EventArgs e)
    {
        ListView1.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListView1_ItemCommand);
    }


    void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        try
        {
            int bID = int.Parse((String)e.CommandArgument);

            var orders = db.bestellings.Where(b => b.bestelling_id == bID).ToList();

            foreach (bestelling order in orders)
            {
                
                foreach (kaartje kaart in order.kaartjes.ToList())
                {
                    db.kaartjes.Remove(kaart);
                }
                db.SaveChanges();
                db.bestellings.Remove(order);
            }
            db.SaveChanges();
            Response.Redirect( HttpContext.Current.Request.Url.AbsoluteUri );
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
    } 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["db"] != null)
        {
            db = (debioscoopEntities)Session["db"];
        }

        if (Master.getUser() != null)
        {
            var account = Master.getUser();

            if (account.tussenvoegsel.Trim().Equals(""))
            {
                lblName.Text = account.voornaam + " " + account.achternaam;
            }
            else
            {
                lblName.Text = account.voornaam + " " + account.tussenvoegsel + " " + account.achternaam;
            }

            lblDateOfBirth.Text = account.geboortedatum.ToString("d/M/yyyy");
            lblAddress.Text = account.straat + " " + account.huisnummer;
            lblPostal.Text = account.postcode;
            lblGender.Text = account.geslacht;

            //lblPassword.Text = account.wachtwoord;
            lblUserName.Text = account.gebruikersnaam;
            lblEMail.Text = account.email;

            if (account.taal.Equals("EN"))
            {
                lblLanguage.Text = "English";
            }
            else if (account.taal.Equals("NL"))
            {
                lblLanguage.Text = "Nederlands";
            }
            else
            {
                lblLanguage.Text = "Geen taal gevonden";
            }

            if (account.abbonement != null)
            {
                lblSubscription.Text = account.abbonement.abbonementnaam;
            }
            else
            {
                lblSubscription.Text = "U heeft nog geen abonnement";
            }

            if (account.nieuwsbrief)
            {
                lblNewsletter.Text = "Ja";
            }
            else
            {
                lblNewsletter.Text = "Nee";
            }

            if (!Page.IsPostBack)
            {
                string gebruikersnaam = account.gebruikersnaam;
                var hi = from b in db.bestellings
                         where b.account.gebruikersnaam == gebruikersnaam
                         where b.active == true
                         where b.afgehaald == false
                         where b.betaald == false
                         select b;
                ListView1.DataSource = hi.ToList();
                ListView1.DataBind();
            }
        }
        else if (!String.IsNullOrEmpty(Request.QueryString["username"]) && !String.IsNullOrEmpty(Request.QueryString["code"]))
        {
            String ip = Request.ServerVariables["REMOTE_ADDR"];
            String username = Request.QueryString["username"];
            String code = Request.QueryString["code"];

            PasswordManager pm = new PasswordManager();
            if (code.Equals(pm.EncodePassword(ip + username + ip)))
            {
                List<account> accounts = new List<account>();
                accounts = db.accounts.Where(a => a.gebruikersnaam.Equals(username)).ToList();

                if (accounts.Count > 0)
                {
                    accounts[0].actief = true;

                    db.SaveChanges();

                    Response.Redirect("~/Login.aspx?username=" + username);
                }
            }

            lblMessage.Text = Master.tl.getTranslation("notActivedAccount");
        }
        else
        {
            Response.Redirect("~/Login.aspx?redirect=Account.aspx");
        }

        if (!IsPostBack)
        {
            sexDdl.Items.Add(new ListItem(Master.tl.getTranslation("male"), "m"));
            sexDdl.Items.Add(new ListItem(Master.tl.getTranslation("female"), "v"));

            ddlLanguage.Items.Add(new ListItem(Master.tl.getTranslation("dutch"), "NL"));
            ddlLanguage.Items.Add(new ListItem(Master.tl.getTranslation("english"), "EN"));

        }

    }

    public string getCorrectDate(object datum)
    {
        return DateTime.Parse(datum.ToString()).ToString("d/M/yyyy");
    }

    public string getTicketsStrings(object bestellingsID)
    {
        int bID = int.Parse(bestellingsID.ToString());
        var kaart_soortlijst = db.kaart_soort.ToList();
        string strToReturn = null;
        foreach (kaart_soort ks in kaart_soortlijst)
        {
            int ksID = ks.kaart_soort_id;
            int totalKsOrdered = db.kaartjes.Where(b => b.bestellingbestelling_id == bID && b.kaart_soort_id == ksID).Count();
            if (totalKsOrdered > 0)
            {
                if (Master.tl.getCurrentLanguage().Equals("english"))
                {
                    strToReturn += ks.kaart_soort_naam_en + ": " + totalKsOrdered.ToString() + "<br />";

                }
                else
                {
                    strToReturn += ks.kaart_soort_naam + ": " + totalKsOrdered.ToString() + "<br />";
                }

            }

        }
        return strToReturn;
    }

    protected void lnkEditEmail_Click(object sender, EventArgs e)
    {

        var account = Master.getUser();
        List<account> accounts = new List<account>();
        List<String> messages = new List<String>();

        if (emailTxt.Visible)//check if the textbox is visible
        {
            String email = (!emailTxt.Text.Equals("")) ? emailTxt.Text : null;
            if (email != null)
			{
				try
				{
					account.email = email;
					db.SaveChanges();
					lblEMail.Text = account.email;
				}
				catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
				{
					foreach (var validationErrors in dbEx.EntityValidationErrors)
					{
						foreach (var validationError in validationErrors.ValidationErrors)
						{
							System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
						}
					}
				}
			}

            lblMessage.Text = "";

            foreach (String message in messages)
            {
                lblMessage.Text += message + "<br />";
            }

            if (messages.Count > 0)
            {
                lblMessage.CssClass += " show";
            }

            //set textbox to invis
            emailTxt.Visible = !emailTxt.Visible;
            emailTxt.Text = null;
        }
        else//if not visible set textbox to visible
        {
            emailTxt.Visible = !emailTxt.Visible;
        }
    }

    protected void lnkEditName_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        List<account> accounts = new List<account>();
        List<String> messages = new List<String>();

        //nameTxt.Text = account.voornaam;
        //tussenTxt.Text = account.tussenvoegsel;
        //lastTxt.Text = account.achternaam;

        if (nameTxt.Visible && tussenTxt.Visible && lastTxt.Visible)//check if the textbox is visible
        {
            String fname = (!nameTxt.Text.Equals("")) ? nameTxt.Text : null;
            String tname = (!tussenTxt.Text.Equals("")) ? tussenTxt.Text : "";
            String lname = (!lastTxt.Text.Equals("")) ? lastTxt.Text : null;

            if (fname != null && lname != null)
            {
                try
                {
                    account.voornaam = fname;
                    account.tussenvoegsel = tname;
                    account.achternaam = lname;

                    db.SaveChanges();

                    if (account.tussenvoegsel.Trim().Equals(""))
                    {
                        lblName.Text = account.voornaam + " " + account.achternaam;
                    }
                    else
                    {
                        lblName.Text = account.voornaam + " " + account.tussenvoegsel + " " + account.achternaam;
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
            }

            lblMessage.Text = "";

            foreach (String message in messages)
            {
                lblMessage.Text += message + "<br />";
            }

            if (messages.Count > 0)
            {
                lblMessage.CssClass += " show";
            }

            //set textbox to invis
            nameTxt.Visible = !nameTxt.Visible;
            tussenTxt.Visible = !tussenTxt.Visible;
            lastTxt.Visible = !lastTxt.Visible;
            nameTxt.Text = null;
            tussenTxt.Text = null;
            lastTxt.Text = null;
        }
        else//if not visible set textbox to visible
        {
            nameTxt.Visible = !nameTxt.Visible;
            tussenTxt.Visible = !tussenTxt.Visible;
            lastTxt.Visible = !lastTxt.Visible;
        }
    }

    protected void lnkEditAdres_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        List<account> accounts = new List<account>();
        List<String> messages = new List<String>();

        if (adresTxt.Visible && adresNrTxt.Visible)//check if the textbox is visible
        {
            String adres = (!adresTxt.Text.Equals("")) ? adresTxt.Text : null;
            String nr = (!adresNrTxt.Text.Equals("")) ? adresNrTxt.Text : null;
            
            if (adres != null)
            {
                try
                {
                    account.straat = adres;
                    account.huisnummer = nr;
                    db.SaveChanges();

                    lblAddress.Text = account.straat + " " + account.huisnummer;
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
            }

            lblMessage.Text = "";

            foreach (String message in messages)
            {
                lblMessage.Text += message + "<br />";
            }

            if (messages.Count > 0)
            {
                lblMessage.CssClass += " show";
            }

            //set textbox to invis
            adresTxt.Visible = !adresTxt.Visible;
            adresNrTxt.Visible = !adresNrTxt.Visible;
            adresTxt.Text = null;
            adresNrTxt.Text = null;
        }
        else//if not visible set textbox to visible
        {
            adresTxt.Visible = !adresTxt.Visible;
            adresNrTxt.Visible = !adresNrTxt.Visible;
        }
    }

    protected void lnkEditPostcode_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        List<account> accounts = new List<account>();
        List<String> messages = new List<String>();

        if (postTxt.Visible)//check if the textbox is visible
        {
            String postcode = (!postTxt.Text.Equals("")) ? postTxt.Text : null;
            if (postcode != null)
            {
                try
                {
                    account.postcode = postcode;
                    db.SaveChanges(); 
                    lblPostal.Text = account.postcode;
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
            }

            lblMessage.Text = "";

            foreach (String message in messages)
            {
                lblMessage.Text += message + "<br />";
            }

            if (messages.Count > 0)
            {
                lblMessage.CssClass += " show";
            }

            //set textbox to invis
            postTxt.Visible = !postTxt.Visible;
            postTxt.Text = null;
        }
        else//if not visible set textbox to visible
        {
            postTxt.Visible = !postTxt.Visible;
        }
    }

    protected void lnkEditBirth_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        DateTime birthdate = DateTime.Now;
        if (dateTxt.Visible)
        {
            if (!dateTxt.Equals("") && !dateTxt.Equals("dd-mm-jjjj"))
            {
                int year = 0;
                int month = 0;
                int day = 0;

                String wholeDate = dateTxt.Text;
                String[] splittedBirthDate = wholeDate.Split('-').ToArray();

                if (splittedBirthDate.Length > 1)
                {
                    //Dutch date
                    if (splittedBirthDate[0].Length == 4)
                    {
                        year = int.Parse(splittedBirthDate[0]);
                        month = int.Parse(splittedBirthDate[1]);
                        day = int.Parse(splittedBirthDate[2]);
                    }
                    //English date
                    else if (splittedBirthDate[2].Length == 4)
                    {
                        year = int.Parse(splittedBirthDate[2]);
                        month = int.Parse(splittedBirthDate[1]);
                        day = int.Parse(splittedBirthDate[0]);
                    }

                    birthdate = new DateTime(year, month, day);
                    try
                    {
                        account.geboortedatum = birthdate;
                        db.SaveChanges();
                        lblDateOfBirth.Text = account.geboortedatum.ToString("d/M/yyyy");
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            }
                        }
                    }
                }
            }

            dateTxt.Visible = !dateTxt.Visible;
        }
        else
        {
            dateTxt.Visible = !dateTxt.Visible;
        }
    }

    protected void lnkEditGender_Click(object sender, EventArgs e)
    {

        var account = Master.getUser();
        String sex = sexDdl.SelectedItem.Value;
        
        try
        {
            account.geslacht = sex;
            db.SaveChanges();
            lblGender.Text = account.geslacht;
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
        
    }

    protected void lnkEditLanguage_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        String language = ddlLanguage.SelectedItem.Value;

        try
        {
            account.taal = language;
            db.SaveChanges(); 
            if (account.taal.Equals("EN"))
            {
                lblLanguage.Text = "English";
            }
            else if (account.taal.Equals("NL"))
            {
                lblLanguage.Text = "Nederlands";
            }
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
    }

    protected void lnkEditLetter_Click(object sender, EventArgs e)
    {
        var account = Master.getUser();
        bool newsletter = cbNewsletter.Checked;

        if (cbNewsletter.Visible)
        {
            try
            {
                account.nieuwsbrief = newsletter;
                db.SaveChanges();
                if (account.nieuwsbrief)
                {
                    lblNewsletter.Text = "Ja";
                }
                else
                {
                    lblNewsletter.Text = "Nee";
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            cbNewsletter.Visible = !cbNewsletter.Visible;
        }
        else
        {
            cbNewsletter.Visible = !cbNewsletter.Visible;
        }

    }
    
}